/*
 	Script: GearsORM.Transaction.js
 	        Contains a function to run queries in a transaction.
 	
 	License:
 	        MIT-style license.
*/

/*
 Function: GearsORM.Transaction
 	execute a function while running queries in a transaction.
 	adapted from TrimPath Junction db.transact
 	
 Parameters:
 	fn - function to run
 	bind - the object that will be "this" in the function 
 */
GearsORM.Transaction = function(fn,bind)
{
	try
	{
		if(GearsORM.Transaction.depth <= 0)
			GearsORM.execute("BEGIN");
		GearsORM.Transaction.depth++;
		fn.apply(bind || this,[]);
	}
	catch(e)
	{
		GearsORM.Transaction.depth = 0;
		GearsORM.execute("ROLLBACK");
		throw e;
	}
	GearsORM.Transaction.depth = Math.max(0, GearsORM.Transaction.depth - 1);
	if (GearsORM.Transaction.depth <= 0)
		GearsORM.execute("COMMIT");
};
GearsORM.Transaction.depth = 0;